package io.github.idol.login

import android.app.Application
import android.arch.lifecycle.AndroidViewModel
import android.databinding.ObservableField
import android.text.TextUtils
import android.util.Log
import com.blankj.utilcode.util.SPUtils
import com.google.gson.Gson
import io.github.idol.data.ApiRepository
import io.github.idol.Constants
import io.github.idol.utils.RxJavaUtils
import io.github.idol.SingleLiveEvent

/**
 * Created by codeczx on 2018/7/31 下午 11:16.
 * Class description:
 */

class LoginViewModel(application: Application,private val apiRepository: ApiRepository):AndroidViewModel(application){
    val username = ObservableField<String>()
    val password = ObservableField<String>()
    private val navigateToMain = SingleLiveEvent<Boolean>()

    fun login(){
        val un = username.get()?:""
        val pw = password.get()?:""
        Log.i("loginviewmodel","un"+un)

        apiRepository.login(un, pw)
                .compose(RxJavaUtils.flowableAppleNetworkSchedulers())
                .subscribe({
                    when (it.status) {
                        200 -> {
                            val spUtils = SPUtils.getInstance(Constants.SP_NAME)
                            spUtils.put(Constants.SP_USERNAME,un)
                            spUtils.put(Constants.SP_PASSWORD,pw)
                            it.content?.token?.let {
                                spUtils.put(Constants.HEADER_KEY_TOKEN,it)
                            }
                            spUtils.put(Constants.SP_FRIENDS, Gson().toJson(it.content?.friends))
                            navigateToMain.value = true
                        }
                    }
                },Throwable::printStackTrace)
    }

    fun getNavigateToMain(): SingleLiveEvent<Boolean> {
        return navigateToMain
    }

    fun start(){
        val spUtils = SPUtils.getInstance(Constants.SP_NAME)
        if(!TextUtils.isEmpty(spUtils.getString(Constants.SP_USERNAME,""))){
            navigateToMain.value = true
        }
    }
}